package com.dong.controller;

import com.dong.base.BaseController;
import com.dong.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController extends BaseController {

    @Autowired
    UserService userService;

    @RequestMapping("/loginPage")
    public String loginPage(HttpServletRequest request) {
        return "login";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request) {
        Object errorMsg2 = request.getAttribute("shiroLoginFailure");
        logger.error("登录异常信息：" + (errorMsg2 == null ? "null" : errorMsg2.toString()));
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return "redirect:/index";
        } else {
            return "redirect:/loginPage";
        }
    }

    @RequestMapping("/doLogin")
//    @ResponseBody
    public String doLogin(String username, String password, HttpServletRequest request) {
        Object errorMsg = request.getSession().getAttribute("errorMsg");
        Object errorMsg2 = request.getAttribute("shiroLoginFailure");
        logger.info(errorMsg == null ? "null" : errorMsg.toString());
        logger.info("登录异常信息：" + (errorMsg2 == null ? "null" : errorMsg2.toString()));
        if (StringUtils.isEmpty(errorMsg2)) {
            return "redirect:/index";
        } else {
            return "redirect:/login";
        }
//        User user = new User();
//        user.setUsername(username);
//        String md5Password = MD5Util.MD5Encode(password);
//        user.setPassword(md5Password);
//        logger.info("username=" + username + ";password=" + password);
//        if (userService.checkPassword(user)) {
//            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, md5Password));
//            return "redirect:/index";
//        }
//        request.getSession().setAttribute("errorMsg", "用户名或密码错误!");
//        return "redirect:/login";
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/index";
    }
}
